package com.cloudfast.config.dateFormat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

/**
 * @author liuyw
 * @描述:日期格式
 * @date 2020年4月30日
 */
@Configuration
public class DateConverterConfig implements Converter<String, Date> {
    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    private static final List<String> FORMARTS = new ArrayList<>(4);

    static {
        FORMARTS.add("yyyy-MM");
        FORMARTS.add("yyyy-MM-dd");
        FORMARTS.add("yyyy-MM-dd hh:mm");
        FORMARTS.add("yyyy-MM-dd HH:mm:ss");
    }

    @Override
    public Date convert(String source) {
        try {
            String value = source.trim();
            if ("".equals(value)) {
                return null;
            }
            if (source.matches("^\\d{4}-\\d{1,2}$")) {

                return parseDate(source, FORMARTS.get(0));
            } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {

                return parseDate(source, FORMARTS.get(1));
            } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {

                return parseDate(source, FORMARTS.get(2));
            } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {

                return parseDate(source, FORMARTS.get(3));
            } else {
                throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
            }
        } catch (Exception e) {
            return new Date();
        }

    }

    /**
     * 格式化日期
     *
     * @param dateStr String 字符型日期
     * @param format  String 格式
     * @return Date 日期
     */
    public Date parseDate(String dateStr, String format) {
        Date date = null;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            date = dateFormat.parse(dateStr);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return date;
    }

}
